package com.feeyo.monitor.rest;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.feeyo.monitor.domain.Department;
import com.feeyo.monitor.service.*;
import com.feeyo.monitor.utils.DateUtils;
import com.github.pagehelper.PageInfo;
import org.apache.commons.collections4.map.HashedMap;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import com.feeyo.monitor.domain.Vehicle;
import com.feeyo.monitor.domain.VehicleType;
import com.feeyo.monitor.utils.GloabalConstant;
import com.feeyo.monitor.utils.ParseUtils;
import com.feeyo.monitor.utils.ResultData;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


/**
 * 车辆相关rest接口服务
 * @Author <a href="mailto:bliulei@variflight.com">liulei</a>
 * @Description Created by liulei on 2017/5/18 下午5:42.
 */
@RestController
@RequestMapping("/")
@CrossOrigin
public class VehicleController {
	
	@Autowired
	UserVehiclePermissionService userVehiclePermissionService;
	@Autowired
	VehicleService vehicleService;
	@Autowired
	VehicleHourlyArchiveService vehicleHourlyArchiveService;
	@Autowired
	VehicleTypeService vehicleTypeService;
	@Autowired
	ExcelParserService excelParserService;
	@Autowired
    VehicleEventService vehicleEventService;
	@Autowired
    DepartmentService departmentService;
	@Autowired
    VehicleTrackingService vehicleTrackingService;


	/**
	 * @Description 获取车辆列表(监控端)
	 * @params 
	 * @return 
	 */
	@RequestMapping(value="/monitor/vehicles", method=RequestMethod.GET)
	public ResultData<List<Vehicle>> getVehicle(@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value = "vehicleType",required=false) String vehicleType,
			@RequestParam(value = "number",required=false) String number){
		ResultData<List<Vehicle>> rd = new ResultData<List<Vehicle>>();
		try{
			Map<Object, Object> perm = userVehiclePermissionService.selectByUserId(userId);
			Map<String,Object> param = ParseUtils.parsePermsMap(perm);
			if (vehicleType != null) {
			    if(!vehicleType.equals("")) {
                    String[] res = vehicleType.split(",");
                    List<String> vehList = new ArrayList<String>();
                    for (String rr : res)
                        vehList.add(rr);
                    param.put("vehicletype", vehList);
                    System.out.println("------->" + vehicleType);
                    System.out.println("22------->" + vehList.size());
                }
            }
			if (number != null)
			    param.put("number",number);

			List<Vehicle> result = vehicleService.selectByUser(param);
			rd.setCode(GloabalConstant.SUCCESS);
			rd.setData(result);
			return rd;
		}catch (Exception e){
			rd.setCode(GloabalConstant.FAILED);
			rd.setMessage(e.getMessage());
			e.printStackTrace();
			return rd;
		}

	}


	
	/**
	 * @Description 车辆运行统计
	 * @params 
	 * @return 
	 */
	@RequestMapping(value="/monitor/vehicleRunning", method=RequestMethod.GET)
	public ResultData<PageInfo> vehicleRunning(@RequestParam(value="userId",required=true) String userId,
			@RequestParam(value = "vehicleType",required=false) String vehicleType,
			@RequestParam(value = "number",required=false) String number,
            @RequestParam(value = "deptId",required=false) String deptId,
			@RequestParam(value = "startTime",required=true) String startTime,
			@RequestParam(value = "endTime",required=true) String endTime,
			@RequestParam(value = "pageNumber",required=true) int pageNumber,
			@RequestParam(value = "pageSize",required=true) int pageSize){
		ResultData<PageInfo> rd = new ResultData<PageInfo>();
		Map<Object, Object> perm = userVehiclePermissionService.selectByUserId(userId);
        Map<String,Object> param = ParseUtils.parsePermsMap(perm);
		if (vehicleType != null)
			param.put("vehicleType", vehicleType);
		if (number != null)
			param.put("number", number);
		if (deptId != null){
		    List<String> deptList = departmentService.selectTreeNode(deptId);
		    param.put("deptList",deptList);
        }

		param.put("startTime", startTime);
		param.put("endTime", endTime);
		PageInfo result = null;
		try{
			result = vehicleHourlyArchiveService.vehicleRunning(param, pageNumber, pageSize);
		}catch (Exception e){
			rd.setCode(GloabalConstant.FAILED);
			rd.setMessage(e.getMessage());
			e.printStackTrace();
			return rd;
		}
		rd.setCode(GloabalConstant.SUCCESS);
		rd.setData(result);
		return rd;
	}


    /**
     * @Description 车辆运行统计
     * @params
     * @return
     */
    @RequestMapping(value="/monitor/vehicleHighCycleStat", method=RequestMethod.GET)
    public ResultData<List<Map>> vehicleHighCycleStat(@RequestParam(value = "vehicleType",required=false) String vehicleType,
                                               @RequestParam(value = "deptId",required=false) String deptId,
                                               @RequestParam(value = "startTime",required=true) String startTime,
                                               @RequestParam(value = "endTime",required=true) String endTime) {
        ResultData<List<Map>> rd = new ResultData<List<Map>>();
        Map<String,Object> param = new HashMap<>();
        if (vehicleType != null)
            param.put("vehicleType", vehicleType);
        if (deptId != null){
            List<String> deptList = departmentService.selectTreeNode(deptId);
            param.put("deptList",deptList);
        }
        param.put("startTime", startTime);
        param.put("endTime", endTime);
        List<Map> result = null;
        Integer count = 0;
        try{
            result = vehicleHourlyArchiveService.vehicleHighCycleStat(param);
            count = vehicleService.selectCount(param);
            final Integer all = count;
            result.forEach(map -> {
                map.put("all",all);
                if(all >0) {
                    Float u = Float.parseFloat(map.get("count").toString());
                    Float d = Float.parseFloat(all.toString());
                    Float r = u/d;
                    Float e = (float)Math.round(r*100)/100;
                    map.put("rate",e);
                }
            });
        }catch (Exception e){
            rd.setCode(GloabalConstant.FAILED);
            rd.setMessage(e.getMessage());
            e.printStackTrace();
            return rd;
        }
        rd.setCode(GloabalConstant.SUCCESS);
        rd.setData(result);
        return rd;
    }

	/**
	 * 车辆类型列表
	 * @param userId
	 * @return
	 */
	@RequestMapping(value="/monitor/vehicleType", method=RequestMethod.GET)
	public ResultData<List<VehicleType>> vehicleType(@RequestParam(value="userId",required=true) String userId){

		ResultData<List<VehicleType>> rd = new ResultData<List<VehicleType>>();
		try{
            if("".equals(userId)){
                List<VehicleType> result = vehicleTypeService.selectByUser(null);
                rd.setCode(GloabalConstant.SUCCESS);
                rd.setData(result);
            }else {
                Map<Object, Object> perm = userVehiclePermissionService.selectByUserId(userId);
                Map<String, Object> param = ParseUtils.parsePermsMap(perm);
                //获取车辆
                Map<String, Object> vParam = ParseUtils.parsePermsMap(perm);
                List<Vehicle> vResult = vehicleService.selectByUser(vParam);

                Set<String> vehTypeId = new HashSet<>();
                for (Vehicle v : vResult) {
                    vehTypeId.add(v.getVehicleType());
                }
                if(vehTypeId.size() == 0)
                    param.put("vehicletype", null);
                else
                    param.put("vehicletype", vehTypeId);

                List<VehicleType> result = vehicleTypeService.selectByUser(param);
                rd.setCode(GloabalConstant.SUCCESS);
                rd.setData(result);
            }

			return rd;
		}catch (Exception e){
		    e.printStackTrace();
			rd.setCode(GloabalConstant.FAILED);
			rd.setMessage(e.getMessage());
			return rd;
		}
	}

    @RequestMapping(value="/monitor/vehicleTypeByDept", method=RequestMethod.GET)
    public ResultData<List> vehicleTypeByDept(@RequestParam(value="deptIds",required=true) String deptIds){
        ResultData<List> rd = new ResultData<List>();
        try{
            List<String> deptList = Arrays.asList(deptIds.split(","));

            List result = vehicleTypeService.selectByDept(deptList);
            rd.setCode(GloabalConstant.SUCCESS);
            rd.setData(result);
            return rd;
        }catch (Exception e){
            e.printStackTrace();
            rd.setCode(GloabalConstant.FAILED);
            rd.setMessage(e.getMessage());
            return rd;
        }
    }

    @RequestMapping(value="/monitor/vehicle/track", method=RequestMethod.GET)
    public ResultData<List> vehicleTrack(@RequestParam(value="vehicleId",required=true) String vehicleId,
                                         @RequestParam(value="startTime",required=true) String startTime,
                                         @RequestParam(value="endTime",required=true) String endTime){
        ResultData<List> rd = new ResultData<List>();
        try{
            List result = vehicleTrackingService.getTrackingByVehicle(vehicleId,DateUtils.getUtcDateTimeStr(startTime),DateUtils.getUtcDateTimeStr(endTime));
            rd.setCode(GloabalConstant.SUCCESS);
            rd.setData(result);
            return rd;
        }catch (Exception e){
            rd.setCode(GloabalConstant.FAILED);
            rd.setMessage(e.getMessage());
            return rd;
        }
    }
    
	/**
	 * @Description 获取车辆列表(管理端)
	 * @params 
	 * @return 
	 */
	@RequestMapping(value="/manager/vehicles", method=RequestMethod.GET)
	public ResultData<PageInfo> getVehicles(@RequestParam(value="deptId",required=false) String deptId,
                                                @RequestParam(value = "searchParam",required=false) String searchParam,
												@RequestParam(value = "pageNumber",required=true) int pageNumber,
												@RequestParam(value = "pageSize",required=true) int pageSize){
		ResultData<PageInfo> rd = new ResultData<PageInfo>();
		Map<String,Object> param = new HashMap<>();
		if (deptId != null) {
            List<String> depList = departmentService.selectTreeNode(deptId);
            param.put("depList", depList);
        }
        if (searchParam != null)
            param.put("searchParam", searchParam);
		PageInfo page = null;
		try{
			page = vehicleService.selectByPage(param,pageNumber,pageSize);
		}catch (Exception e){
			rd.setCode(GloabalConstant.FAILED);
			rd.setMessage(e.getMessage());
			e.printStackTrace();
			return rd;
		}

		rd.setCode(GloabalConstant.SUCCESS);
		rd.setData(page);
		return rd;
	}

	/**
	 * @Description 获取车辆详细信息
	 * @params
	 * @return 
	 */
	@RequestMapping(value="/manager/vehicles/{vehicleId}", method=RequestMethod.GET)
	public ResultData<Vehicle> getVehicle(@PathVariable(value="vehicleId",required=true) String vehicleId){
		ResultData<Vehicle> rd = new ResultData<Vehicle>();
		Vehicle vehicle = null;
		try{
			vehicle = vehicleService.selectByPrimaryKey(vehicleId);
		}catch (Exception e){
			rd.setCode(GloabalConstant.FAILED);
			rd.setMessage(e.getMessage());
			e.printStackTrace();
			return rd;
		}
		rd.setCode(GloabalConstant.SUCCESS);
		rd.setData(vehicle);
		return rd;
	}

	/**
	 * @Description 新增/修改车辆
	 * @params 
	 * @return 
	 */
	@RequestMapping(value="/manager/vehicles", method=RequestMethod.POST)
	public ResultData<Object> saveVehicle(@ModelAttribute("vehicle")  Vehicle vehicle){
		ResultData<Object> rd = new ResultData<Object>();
		try {
			if ((vehicle.getId() == null) || (vehicle.getId().equals(""))) {
			    vehicle.setCreateTime(new Date());
				vehicleService.insert(vehicle);
			} else {
				vehicleService.updateByPrimaryKeySelective(vehicle);
			}
		}catch (Exception e){
			rd.setCode(GloabalConstant.FAILED);
			rd.setMessage(e.getMessage());
			e.printStackTrace();
			return rd;
		}
		rd.setCode(GloabalConstant.SUCCESS);
		return rd;
	}
	
    /**
     * @Description 删除车辆
     * @params 
     * @return 
     */
	@RequestMapping(value="/manager/vehicles/delete/{vehicleId}", method=RequestMethod.GET)
	public ResultData<Object> delete(@PathVariable("vehicleId")String vehicleId){
		ResultData<Object> rd = new ResultData<Object>();
		try{
			vehicleService.updateDeleteStatus(vehicleId);
		}catch(Exception e){
			rd.setCode(GloabalConstant.FAILED);
			rd.setMessage(e.getMessage());
			e.printStackTrace();
			return rd;
		}
		rd.setCode(GloabalConstant.SUCCESS);
		return rd;
	}

    /**
     * @Description 删除告警记录
     * @params
     * @return
     */
    @RequestMapping(value="/manager/alarm/delete/{eventId}", method=RequestMethod.GET)
    public ResultData<Object> delete(@PathVariable("eventId")Integer eventId){
        ResultData<Object> rd = new ResultData<Object>();
        try{
            vehicleEventService.updateDeleteStatus(eventId);
        }catch(Exception e){
            rd.setCode(GloabalConstant.FAILED);
            rd.setMessage(e.getMessage());
            e.printStackTrace();
            return rd;
        }
        rd.setCode(GloabalConstant.SUCCESS);
        return rd;
    }
    
	/**
	 * @Description 导入车辆信息（excel格式）
	 * @params 
	 * @return 
	 */
	@RequestMapping(value="/manager/vehicles/import", method=RequestMethod.POST)
	public ResultData<Object> excelImport(@RequestParam("file") MultipartFile file){
		ResultData<Object> rd = new ResultData<Object>();
		if(file.isEmpty()){
			rd.setCode(GloabalConstant.FILE_IS_NULL);
			rd.setMessage("文件为空");
		}else{
			String fileName = file.getOriginalFilename();
			// 获取文件的后缀名
			String suffixName = fileName.substring(fileName.lastIndexOf("."));

			try {
				InputStream stream = file.getInputStream();
				excelParserService.parse(stream);
			} catch (IOException e) {
				e.printStackTrace();
				rd.setCode(GloabalConstant.FAILED);
                rd.setMessage(e.getMessage());
                return rd;
            }
		}
		return rd;
	}

	/**
	 * @Description 告警记录
	 * @params 
	 * @return 
	 */
    @RequestMapping(value="/monitor/alarms", method=RequestMethod.GET)
    public ResultData<PageInfo> alarmEvent(@RequestParam(value="alarmType",required=false) Integer alarmType,
                                      @RequestParam(value="vehicleType",required=false) String vehicleType,
                                      @RequestParam(value="number",required=false) String number,
                                      @RequestParam(value="startTime",required=false) String startTime,
                                      @RequestParam(value="endTime",required=false) String endTime,
                                      @RequestParam(value="deptId",required=false) String deptId,
                                      @RequestParam(value="pageNumber",required=true) int pageNumber,
                                      @RequestParam(value="pageSize",required=true) int pageSize){
        ResultData<PageInfo> rd = new ResultData<PageInfo>();
        Map<String,Object> param = new HashMap<String,Object>();
        if (alarmType != null)
            param.put("alarmType",alarmType);
        if (vehicleType != null)
            param.put("vehicleType",vehicleType);
        if (number != null)
            param.put("number",number);
        if (startTime != null){
            try {
                Long timestamp = DateUtils.dateTimeToStamp(startTime);
                param.put("startTime",timestamp);
            } catch (ParseException e) {
                e.printStackTrace();
                rd.setCode(GloabalConstant.DATE_FORMAT_ERROR);
                return rd;
            }
        }

        if (endTime != null){
            try {
                Long timestamp = DateUtils.dateTimeToStamp(endTime);
                param.put("endTime",timestamp);
            } catch (ParseException e) {
                e.printStackTrace();
                rd.setCode(GloabalConstant.DATE_FORMAT_ERROR);
                return rd;
            }
        }
        if (deptId != null){
            List<String> deptList = departmentService.selectTreeNode(deptId);
            param.put("deptList",deptList);
        }
        PageInfo result = null;
        try {
            result = vehicleEventService.selectByPage(param, pageNumber, pageSize);
        }catch (Exception e){
            e.printStackTrace();
            rd.setCode(GloabalConstant.FAILED);
            rd.setMessage(e.getMessage());
            return rd;
        }
        rd.setCode(GloabalConstant.SUCCESS);
        rd.setData(result);
        return rd;
    }

    /**
     * @Description 修改车辆状态
     * @params 
     * @return 
     */
    @RequestMapping(value="/manager/vehicleStatus", method=RequestMethod.GET)
    public ResultData<Object> vehicleStatus(@RequestParam(value="vehicleId",required=true) String vehicleId,
                                                 @RequestParam(value = "vehicleStatus",required=true) Short vehicleStatus){
        ResultData<Object> rd = new ResultData<Object>();
        Map param = new HashedMap();
        param.put("vehicleId",vehicleId);
        param.put("vehicleStatus",vehicleStatus);
        try {
            vehicleService.updateVehicleStatus(param);
        }catch (Exception e){
            e.printStackTrace();
            rd.setCode(GloabalConstant.FAILED);
            rd.setMessage(e.getMessage());
            return rd;
        }
        rd.setCode(GloabalConstant.SUCCESS);
        return rd;
    }

    @RequestMapping(value="/monitor/ifonline", method=RequestMethod.GET)
    public String ifOnline(@RequestParam(value="number",required=true) String number){
        String id = vehicleService.selectDevidByNumber(number);
        boolean result  = vehicleTrackingService.ifOnline(id);
        if (result)
            return "有数据";
        else
            return "无数据";
    }


    @RequestMapping(value="/manager/export/dept", method=RequestMethod.GET)
    public ResultData<Object> exportDept(HttpServletRequest request, Model model) throws Exception{
        ResultData<Object> rd = new ResultData<>();
        List<Map> result = vehicleService.selectExportAll();
        for (Map vehicle : result){
            Object uuid = vehicle.get("department");
            if (uuid == null){
                System.out.println("uuid - null");
                continue;
            }
            String deptId = vehicle.get("department").toString();
            String deptName = "";//(String)vehicle.get("deptname");
            Department  dt = departmentService.selectByPrimaryKey(deptId);
            deptName = dt.getName() + "-"+ deptName;
            while (dt.getParentid() != null){
                dt = departmentService.selectByPrimaryKey(dt.getParentid().toString());
                deptName = dt.getName() + "-"+ deptName;
            }

            deptName = deptName.substring(0,deptName.length()-1);
            System.out.println("deptName->"+deptName);
            vehicle.put("deptname",deptName);
        }
        rd.setData(result);
        return rd;
    }

    @RequestMapping(value="/manager/export", method=RequestMethod.GET)
    public ResponseEntity<byte[]> export(HttpServletRequest request, Model model) throws Exception{
        String path = request.getSession().getServletContext().getRealPath("");
        System.out.println("file->" + path);
        List<Map> result = vehicleService.selectExportAll();

        for (Map vehicle : result){
            Object uuid = vehicle.get("department");
            if (uuid == null){
                System.out.println("uuid - null");
                continue;
            }
            String deptId = vehicle.get("department").toString();
            String deptName = "";
            Department  dt = departmentService.selectByPrimaryKey(deptId);
            if(dt != null) {
                deptName = dt.getName() + "-" + deptName;
                while (dt.getParentid() != null) {
                    dt = departmentService.selectByPrimaryKey(dt.getParentid().toString());
                    deptName = dt.getName() + "-" + deptName;
                }
                deptName = deptName.substring(0, deptName.length() - 1);
                System.out.println("deptName->" + deptName);
                vehicle.put("deptname", deptName);
            }
        }

        String filename = excelParserService.createVehicleExcel(result,path);

        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = null;
        try {
            downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                    headers, HttpStatus.CREATED);

    }

    @RequestMapping(value="/manager/exportPage", method=RequestMethod.GET)
    public ResponseEntity<byte[]> exportPage(HttpServletRequest request, Model model,
                                             @RequestParam(value="deptId",required=false) String deptId,
                                             @RequestParam(value = "searchParam",required=false) String searchParam,
                                             @RequestParam(value = "pageNumber",required=true) int pageNumber,
                                             @RequestParam(value = "pageSize",required=true) int pageSize) throws Exception{
        Map<String,Object> param = new HashMap<>();
        if (deptId != null) {
            List<String> depList = departmentService.selectTreeNode(deptId);
            param.put("depList", depList);
        }
        if (searchParam != null)
            param.put("searchParam", searchParam);

        String path = request.getSession().getServletContext().getRealPath("");
        System.out.println("file->" + path);
        List<Map> result = vehicleService.selectExportPage(param,pageNumber,pageSize);

        for (Map vehicle : result){
            Object uuid = vehicle.get("department");
            if (uuid == null){
                System.out.println("uuid - null");
                continue;
            }
            String curDeptId = vehicle.get("department").toString();
            String deptName = "";
            Department  dt = departmentService.selectByPrimaryKey(curDeptId);
            deptName = dt.getName() + "-"+ deptName;
            while (dt.getParentid() != null){
                dt = departmentService.selectByPrimaryKey(dt.getParentid().toString());
                deptName = dt.getName() + "-"+ deptName;
            }
            deptName = deptName.substring(0,deptName.length()-1);
            System.out.println("deptName->"+deptName);
            vehicle.put("deptname",deptName);
        }

        String filename = excelParserService.createVehicleExcel(result,path);


        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = null;
        try {
            downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);

    }

    /**
     * @Description 车辆运行统计导出
     * @params
     * @return
     */
    @RequestMapping(value="/monitor/vehicleRunningExport", method=RequestMethod.GET)
    public ResponseEntity<byte[]> vehicleRunningExport(HttpServletRequest request,
                                                @RequestParam(value="userId",required=true) String userId,
                                               @RequestParam(value = "vehicleType",required=false) String vehicleType,
                                               @RequestParam(value = "number",required=false) String number,
                                               @RequestParam(value = "deptId",required=false) String deptId,
                                               @RequestParam(value = "startTime",required=true) String startTime,
                                               @RequestParam(value = "endTime",required=true) String endTime,
                                               @RequestParam(value = "pageNumber",required=true) int pageNumber,
                                               @RequestParam(value = "pageSize",required=true) int pageSize)throws Exception{
        String path = request.getSession().getServletContext().getRealPath("");
        Map<Object, Object> perm = userVehiclePermissionService.selectByUserId(userId);
        Map<String,Object> param = ParseUtils.parsePermsMap(perm);
        if (vehicleType != null)
            param.put("vehicleType", vehicleType);
        if (number != null)
            param.put("number", number);
        if (deptId != null){
            List<String> deptList = departmentService.selectTreeNode(deptId);
            param.put("deptList",deptList);
        }

        param.put("startTime", startTime);
        param.put("endTime", endTime);
        PageInfo result = null;
        try{
            result = vehicleHourlyArchiveService.vehicleRunning(param, pageNumber, pageSize);
        }catch (Exception e){
            e.printStackTrace();
        }

        String filename = excelParserService.exportRunnings(result.getList(),path);


        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = null;
        try {
            downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);

    }


    /**
     * @Description 告警记录导出
     * @params
     * @return
     */
    @RequestMapping(value="/monitor/alarmsExport", method=RequestMethod.GET)
    public ResponseEntity<byte[]> alarmExport(HttpServletRequest request,
                                              @RequestParam(value="alarmType",required=false) Integer alarmType,
                                           @RequestParam(value="vehicleType",required=false) String vehicleType,
                                           @RequestParam(value="number",required=false) String number,
                                           @RequestParam(value="startTime",required=false) String startTime,
                                           @RequestParam(value="endTime",required=false) String endTime,
                                           @RequestParam(value="deptId",required=false) String deptId,
                                           @RequestParam(value="pageNumber",required=true) int pageNumber,
                                           @RequestParam(value="pageSize",required=true) int pageSize)throws Exception{
        String path = request.getSession().getServletContext().getRealPath("");
        ResultData<PageInfo> rd = new ResultData<PageInfo>();
        Map<String,Object> param = new HashMap<String,Object>();
        if (alarmType != null)
            param.put("alarmType",alarmType);
        if (vehicleType != null)
            param.put("vehicleType",vehicleType);
        if (number != null)
            param.put("number",number);
        if (startTime != null){
            try {
                Long timestamp = DateUtils.dateTimeToStamp(startTime);
                param.put("startTime",timestamp);
            } catch (ParseException e) {
                e.printStackTrace();

            }
        }

        if (endTime != null){
            try {
                Long timestamp = DateUtils.dateTimeToStamp(endTime);
                param.put("endTime",timestamp);
            } catch (ParseException e) {
                e.printStackTrace();

            }
        }
        if (deptId != null){
            List<String> deptList = departmentService.selectTreeNode(deptId);
            param.put("deptList",deptList);
        }
        PageInfo result = null;
        try {
            result = vehicleEventService.selectByPage(param, pageNumber, pageSize);
        }catch (Exception e){
            e.printStackTrace();

        }

        String filename = excelParserService.exportAlarms(result.getList(),path);

        File file = new File(path + File.separator + filename);
        HttpHeaders headers = new HttpHeaders();
        //下载显示的文件名，解决中文名称乱码问题
        String downloadFielName = null;
        try {
            downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //通知浏览器以attachment（下载方式）打开图片
        headers.setContentDispositionFormData("attachment", downloadFielName);
        //application/octet-stream ： 二进制流数据（最常见的文件下载）。
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }

    @RequestMapping(value="/manager/vehicles/in3s", method=RequestMethod.GET)
    public ResultData<Object> in3s(){
        //
        return null;
    }

    /**
     * @Description 日期参数提交转换
     * @params
     * @return
     */
    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
    }

}
